﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Azure.TableQuery.Core;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.CodeDom.Compiler;
using Azure.TableQuery.Core.Interfaces;

namespace Azure.TableQuery.Tests
{
    
    [TestClass]
    public class QueryActivatorFixture : BaseTest
    {
        GenericEntity entity;
        public QueryActivatorFixture()
            : base()
        {
            var tableClient = new CloudTableClient(@"http://ipv4.fiddler:10002/devstoreaccount1",
                account.Credentials);

            var context = new GenericTableContext(tableClient.BaseUri.ToString(), account.Credentials);
            entity = context.GetFirstOrDefault("TestEntity");

        }

        [TestMethod]
        public void CreateInstance()
        {
            string queryText = "from te in TestEntity where te.Age == 3 select te";
            var compiler = new QueryCompiler(entity, queryText);
            var results = compiler.Compile();

            foreach (CompilerError error in results.Errors)
            {
                Console.WriteLine(error.FileName);
                Console.WriteLine(error.ErrorText);
            }

            Assert.IsTrue(results.Errors.Count == 0);

            var assemblyPath = compiler.GetOutputFileName();

            var instance = QueryActivator.CreateInstance(assemblyPath);

            Assert.IsNotNull(instance);
            Assert.IsInstanceOfType(instance, typeof(IQueryContextFactory));

            var tableClient = new CloudTableClient(@"http://ipv4.fiddler:10002/devstoreaccount1",
              account.Credentials);

            var query = instance.CreateQueryContext(tableClient.BaseUri.ToString(), account.Credentials);
            //var queryResults = query.ExecuteQuery();
            //Assert.IsTrue(queryResults.Count() == 1);
        }
    }
}
